package org.hitchhike.web.front.controller;

import javax.servlet.http.HttpServletRequest;

import org.hitchhike.common.domain.BaseEntity;
import org.hitchhike.common.web.controller.BaseController;
import org.hitchhike.core.domain.Order;
import org.hitchhike.core.domain.OrderDetail;
import org.hitchhike.core.domain.User;
import org.hitchhike.core.enums.Constant;
import org.hitchhike.core.exception.BaseException;
import org.hitchhike.core.form.ReserveForm;
import org.hitchhike.core.service.OrderDetailService;
import org.hitchhike.core.service.OrderService;
import org.hitchhike.core.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * 预订
 */

@Controller
@RequestMapping(value = "/front")
public class ReserveController extends BaseController<BaseEntity, Long> {

  @Autowired
  private UserService userService;
  @Autowired
  private OrderService orderService;
  @Autowired
  private OrderDetailService orderDetailService;

  @RequestMapping(value = "/reserve/{type}/{id}", method = RequestMethod.GET)
  public String reserve(Model model, @PathVariable String type, @PathVariable Long id) {
    Order order = orderService.get(id);
    if (order == null) {
      throw new BaseException("没找到您查询的订单...");
    }
    model.addAttribute("order", order);
    model.addAttribute("type", type);
    return viewName("reserve");
  }

  @RequestMapping(value = "/reserve/save", method = RequestMethod.POST)
  public String save(ReserveForm reserveForm, HttpServletRequest request) {
    Order order = orderService.get(reserveForm.getId());
    if (order == null) {
      throw new BaseException("没找到您查询的订单...");
    }

    User user = userService
        .findByUsername(SecurityContextHolder.getContext().getAuthentication().getName());
    try {
      orderDetailService.save(new OrderDetail(order, user, Constant.ORDER_DETAIL_STATE_1));
    } catch (Exception e) {
      throw new BaseException(e.getMessage());
    }

    return redirectToUrl(viewName("/"));
  }

}
